package com.ziyueyuwen.xiniao.controller;

import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.BasicUtil;
import com.suyeer.basic.util.HttpResUtil;
import com.suyeer.basic.util.JsonUtil;
import com.suyeer.basic.util.LogUtil;
import com.suyeer.fastwechat.util.FwBaseUtil;
import com.suyeer.fastwechat.util.FwUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.bean.wx.TbWxUserInfo;
import com.ziyueyuwen.xiniao.dao.TbWxUserInfoMapper;
import com.ziyueyuwen.xiniao.service.ThirdPartService;
import com.ziyueyuwen.xiniao.util.ConstUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ziyueyuwen.xiniao.base.BaseUtil.*;
import static org.apache.commons.codec.CharEncoding.UTF_8;

/**
 * @author jun 2018/10/25
 */
@Controller
@RequestMapping("/wx_api")
public class WxApiController {

    @Autowired
    private TbWxUserInfoMapper tbWxUserInfoMapper;

    @Autowired
    private ThirdPartService thirdPartService;

    @RequestMapping(value = "/oauth2", method = RequestMethod.GET)
    public String oauth2(@RequestParam(ConstUtil.PARAM_CODE) String code,
                         @RequestParam(ConstUtil.PARAM_STATE) String state,
                         @RequestParam(ConstUtil.PARAM_TARGET_URI) String targetUri,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("微信授权中转");
        try {
            String targetUrl = String.format("%s%s?code=%s&state=%s", ConstUtil.REDIRECT, targetUri, code, state);
            hrc.setWxRedirect(targetUrl);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        }
        return hrc.getWxRedirect();
    }

    /**
     * User: jun
     * Date: 2018/1/8
     * Desc: 微信网页授权回调
     */
    @RequestMapping(value = "/callback", method = RequestMethod.GET)
    public String wxAuthCallback(@RequestParam(ConstUtil.PARAM_CODE) String code,
                                 @RequestParam(ConstUtil.PARAM_STATE) String state,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("微信网页授权回调");
        try {
            // check.
            checkParam(ConstUtil.PARAM_CODE, code);
            checkParam(ConstUtil.PARAM_STATE, state);
            // do.
            hrc.setWxRedirect(ConstUtil.REDIRECT + "/");
            JSONObject wxRetObj = FwUtil.getAuthAccessToken(code);
            if (wxRetObj.containsKey(ConstUtil.WX_PARAM_ERR_CODE)) {
                throw new Exception("授权回调失败：" + wxRetObj.toJSONString());
            }
            String accessToken = wxRetObj.getString(ConstUtil.WX_PARAM_ACCESS_TOKEN);
            String openid = wxRetObj.getString(ConstUtil.WX_PARAM_OPENID);
            TbWxUserInfo tbWxUserInfo;
            if (state.equals(ConstUtil.WX_SILENT_AUTH)) {
                // 静默授权
                tbWxUserInfo = tbWxUserInfoMapper.getByOpenid(openid);
                if (tbWxUserInfo == null) {
                    hrc.setWxRedirect(ConstUtil.REDIRECT + ConstUtil.WX_URL_HIGH_AUTH);
                    throw new IllegalAccessException("当前微信用户还未创建账号, 转入高级授权获取微信信息并创建微信账号!");
                }
            } else {
                // 高级授权
                JSONObject wxUserInfoObj = FwUtil.getAuthUserInfoByOath2Api(accessToken, openid);
                tbWxUserInfo = JsonUtil.changeType(wxUserInfoObj, TbWxUserInfo.class);
                tbWxUserInfo.setHeadImgUrl(wxUserInfoObj.getString(ConstUtil.WX_PARAM_HEAD_IMG_URL));
                tbWxUserInfo.setWxUserId(BasicUtil.getUniqueString("wx"));
                if (!tbWxUserInfoMapper.exit(tbWxUserInfo.getOpenid())) {
                    if (!tbWxUserInfoMapper.add(tbWxUserInfo)) {
                        throw new Exception("高级授权创建微信账号失败!");
                    }
                }
            }
            // 系统账号直接登录
            ZyUser zyUser = thirdPartService.getUserMessage(tbWxUserInfo.getWxUserId());
            if (zyUser != null) {
                zyUser.setUserPassword(null);
                hrc.setUserSession(zyUser);
            }
            // 微信账号登录
            hrc.setWxUserSession(tbWxUserInfo);
            hrc.setWxRedirect(ConstUtil.REDIRECT + hrc.getOriginalQueryURI());
            saveSuccessMsgAndData(hrc, true);
        } catch (IllegalAccessException e) {
            LogUtil.info(e.getMessage());
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        }
        return hrc.getWxRedirect();
    }

    @RequestMapping(value = "/wx_push")
    public void wxPush(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<String> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("微信推送流数据");
        try {
            LogUtil.info(IOUtils.toString(request.getInputStream(), UTF_8));
            String echoStr = FwBaseUtil.checkWxRequest(hrc.getReqParams(), "suyeer");
            saveSuccessMsgAndData(hrc, echoStr);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeOnlyResult(hrc);
        }
    }
}
